package cn.zd.demo0;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.zd.demo0.entity.TabUserInfo;
import cn.zd.demo0.util.ContentProviderUserInfoConstant;
import cn.zd.demo0.util.ViewCheckUtil;

public class ContentProviderClientActivity extends AppCompatActivity implements View.OnClickListener {
    EditText et_username;
    EditText et_usernamenew;
    Button btn_insertuser;
    Button btn_queryuser;
    Button btn_queryalluser;
    Button btn_deluser;
    Button btn_delall;
    Button btn_updateuser;
    Button btn_updateuserall;
    TextView tv_userinfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contentproviderclient);
        Toast.makeText(this, this.getClass().getName(), Toast.LENGTH_LONG).show();

        et_username = findViewById(R.id.et_username);
        et_usernamenew = findViewById(R.id.et_usernamenew);
        tv_userinfo = findViewById(R.id.tv_userinfo);
        btn_insertuser = findViewById(R.id.btn_insertuser);
        btn_queryuser = findViewById(R.id.btn_queryuser);
        btn_queryalluser = findViewById(R.id.btn_queryalluser);
        btn_updateuser = findViewById(R.id.btn_updateuser);
        btn_updateuserall = findViewById(R.id.btn_updateuserall);
        btn_deluser = findViewById(R.id.btn_deluser);
        btn_delall = findViewById(R.id.btn_delall);

        btn_insertuser.setOnClickListener(this);
        btn_queryuser.setOnClickListener(this);
        btn_updateuser.setOnClickListener(this);
        btn_updateuserall.setOnClickListener(this);
        btn_queryalluser.setOnClickListener(this);
        btn_deluser.setOnClickListener(this);
        btn_delall.setOnClickListener(this);
    }

    @SuppressLint("Range")
    @Override
    public void onClick(View v) {


        if (v.getId() == R.id.btn_insertuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            TabUserInfo userInfo = new TabUserInfo();
            userInfo.setUserAge(new Random().nextInt(100));
            userInfo.setUserName(userName);
            ContentValues values = new ContentValues();
            values.put("user_name",userInfo.getUserName());
            values.put("user_age",userInfo.getUserAge());
            getContentResolver().insert(ContentProviderUserInfoConstant.CONTENT_URI,values);
            tv_userinfo.setText("插入数据\n" + userInfo.toString());
            Toast.makeText(this, "用户数据插入成功", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_queryuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            Cursor query = getContentResolver().query(ContentProviderUserInfoConstant.CONTENT_URI, null, "user_name=?", new String[]{oldUserName}, null);
            if(query == null) {
                Toast.makeText(this, "查询所有用户数:" + 0, Toast.LENGTH_SHORT).show();
                tv_userinfo.setText("查询指定用户名" + oldUserName + "数据\n 空");
                return ;
            }
            List<TabUserInfo> userInfos = new ArrayList<>();
            while (query.moveToNext()) {
                TabUserInfo info = new TabUserInfo();
                info.setUserId(query.getInt(query.getColumnIndex("user_id")));
                info.setUserName(query.getString(query.getColumnIndex("user_name")));
                info.setUserAge(query.getInt(query.getColumnIndex("user_age")));
                userInfos.add(info);
            }

            Toast.makeText(this, "查询所有用户数:" + userInfos.size(), Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询指定用户名" + oldUserName + "数据\n" + usersToString(userInfos));

        } else if (v.getId() == R.id.btn_queryalluser) {
            Cursor query = getContentResolver().query(ContentProviderUserInfoConstant.CONTENT_URI, null, null,null, null);
            List<TabUserInfo> userInfos = new ArrayList<>();
            while (query.moveToNext()) {
                TabUserInfo info = new TabUserInfo();
                info.setUserId(query.getInt(query.getColumnIndex("user_id")));
                info.setUserName(query.getString(query.getColumnIndex("user_name")));
                info.setUserAge(query.getInt(query.getColumnIndex("user_age")));
                userInfos.add(info);
            }
            Toast.makeText(this, "查询所有用户数:" + userInfos.size(), Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询所有数据\n" + usersToString(userInfos));
        } else if (v.getId() == R.id.btn_updateuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            if (!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this, "请输入新用户名", Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            String newUserName = et_usernamenew.getText().toString();
            ContentValues values = new ContentValues();
            values.put("user_name",newUserName);
            int count = getContentResolver().update(ContentProviderUserInfoConstant.CONTENT_URI,values,"user_name = ?", new String[]{oldUserName});
            Toast.makeText(this, "用户数据更新成功"+count, Toast.LENGTH_SHORT).show();

        } else if (v.getId() == R.id.btn_updateuserall) {
            if (!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this, "请输入新用户名", Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String newUserName = et_usernamenew.getText().toString();
            ContentValues values = new ContentValues();
            values.put("user_name",newUserName);
            int count = getContentResolver().update(ContentProviderUserInfoConstant.CONTENT_URI,values,null,null);
            Toast.makeText(this, "用户数据更新成功"+count, Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_deluser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户id", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            Long id = null;
            try {
                id = Long.parseLong(userName);
            } catch (Exception e) {
                Toast.makeText(this, "请输入有效的用户id（long）", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            Uri uri = ContentUris.withAppendedId(ContentProviderUserInfoConstant.CONTENT_URI, id);
            int count = getContentResolver().delete(uri,null,null);
            Toast.makeText(this, "用户数据删除成功:"+count, Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_delall) {
            int res = getContentResolver().delete(ContentProviderUserInfoConstant.CONTENT_URI,null,null);
            Toast.makeText(this, "所有用户数据删除结果:" + res, Toast.LENGTH_SHORT).show();
        }
    }

    private String usersToString(List<? extends Object> userInfos) {
        if (userInfos == null || userInfos.size() == 0) {
            return "空数据";
        }
        StringBuffer sb = new StringBuffer("\n");
        userInfos.forEach(userInfo -> {
            sb.append(userInfo.toString()).append("\n");
        });
        return sb.toString();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "数据库打开成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}